<template>
  <div class="work-order-pool">
    <Vmask :maskTitle='maskTitle' :maskData='maskData' :showMask='showMask' :maskWidth='maskWidth' @FnMask='FnMask'></Vmask>
    <!-- 工单池 -->
    <div class="search">
      <div class="row clearfix lh40 mt15">
        <div class="row-item clearfix fl mr15 mb15">
          <span class="row-item-title fl">工单编号：</span>
          <span class="fl span-input">
            <el-input placeholder="请输入内容" v-model.trim="orderNo"></el-input>
          </span>
        </div>
        <div class="row-item clearfix fl mr15 mb15">
          <span class="row-item-title fl">客户号码：</span>
          <span class="fl span-input">
            <el-input placeholder="请输入内容" v-model.trim="phoneNum"></el-input>
          </span>
        </div>
        <div class="row-item clearfix fl mr15 mb15">
          <span class="row-item-title fl">ESN编号/订单编号：</span>
          <span class="fl span-input">
            <el-input placeholder="请输入内容" v-model.trim="esnOrderNo"></el-input>
          </span>
        </div>
        <div class="row-item clearfix fl mr15 mb15">
          <span class="row-item-title fl">最后处理人：</span>
          <span class="fl span-input">
            <el-input placeholder="请输入内容" v-model.trim="handlePerson"></el-input>
          </span>
        </div>
      </div>
      <div class="row clearfix">
        <div class="row-item fl mr15 mb15">
          <span class="row-item-title">创建时间：</span>
          <span class="timer">
            <el-date-picker v-model="timer" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </span>
        </div>
        <div class="row-item fl mr15" v-if="shoWorderDeptId">
          <span class="row-item-title">处理部门：</span>
          <span class="">
            <el-select v-model="orderDeptId" clearable placeholder="请选择" style="width:auto">
              <el-option v-for="item in handleDepartmentList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </span>
        </div>
        <div class="row-item fl mr15">
          <span class="row-item-title">工单类型：</span>
          <span class="">
            <el-select v-model="searchWorkOderType" clearable placeholder="请选择" style="width:auto">
              <el-option :value="1" label="紧急"></el-option>
              <el-option :value="2" label="升级"></el-option>
            </el-select>
          </span>
        </div>
        <!-- <div class="row-item fl mr15" style="marginLeft:45px">
          <el-button type="primary"  @click="FnSearch">查询</el-button>
        </div> -->
        <!-- <div class="row-item fl">
          <el-button type="primary">生成工单</el-button>
        </div> -->
      </div>
      <div class="row clearfix lh40 mb15">
        <div class="row-item fl">
          <span class="row-item-title fl">工单分类：</span>
          <span class="fl mr15">
            <el-cascader v-model="classificationName" :options="jobClassificationList" :props="{ checkStrictly: true,label:'label',value:'label' }" clearable></el-cascader>
          </span>
        </div>
        <div class="row-item clearfix fl mr15">
          <span class="row-item-title fl">工单内容：</span>
          <span class="fl span-input">
            <el-input placeholder="请输入内容" v-model.trim="orderContent"></el-input>
          </span>
        </div>
        <div class="row-item fl mr15" style="marginLeft:45px">
          <el-button type="primary" @click="FnSearch">查询</el-button>
        </div>
      </div>
    </div>
    <div class="content-table">
      <div class="content-table-title">
        <div class="row clearfix">
          <div class="row-item fr">
            <el-button type="primary" @click="FnExport" v-if="getPermissionControl.workOrderPoolExport">导出</el-button>
          </div>
        </div>
      </div>
      <ShowTable :tableData='tableData' :selections='selections' :lableList='lableList' :talLength='talLength' :pageSize='pageSize' :pageNum='pageNum' @getSortableFn='getSortableFn'></ShowTable>
    </div>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex';
import ShowTable from '../components/table/show-table'
import Vmask from '@/views/components/v-mask/v-mask'
import { GetWorkOrderByConditions, Code, AddWorkOrder, GetClassificationList, LockWorkOrder, ReleaseWorkOrder, AddAdditionalComment, AddHandleComment } from '@/axios/api'
import { mixin } from '@/mixin/mixin';

export default {
  name: '',
  mixins: [mixin],
  data() {
    return {
      showMask: false,
      maskTitle: '',
      maskWidth: '800px',
      maskData: {},
      orderNo: '',//工单编号：
      phoneNum: '',//客户号码：
      esnOrderNo: '',//ESM编号
      handlePerson: '',//最后处理人：
      timer: '',
      orderStatusFlagList: [
        { label: '成功', value: '1' },
        { label: '失败', value: '2' },
        { label: '待跟进', value: '3' },
        { label: '未处理', value: '4' },
      ],
      orderStatusFlag: '',
      orderDeptId: '',//处理部门
      searchWorkOderType: '',//工单类型
      classificationName: [],//工单分类
      orderContent: '',//工单内容
      shoWorderDeptId: false,
      tableData: [
        // {
        //   overtime:true,
        //   n1:'工单类型11',
        //   n2:'流水号',
        //   n3:'工单编号',
        //   n4:'登记人姓名',
        //   n5:'电话号码',
        //   n6:'创建时间',
        //   n7:'处理部门',
        //   n8:'催单',
        //   n9:'工单状态',
        //   n10:'最后处理人',
        //   additionalComments:true,//附加意见
        //   handlingOpinions:true,//处理意见
        // }
      ],
      selections: false,//是否多选
      lableList: {//表头
        overtime: '是否超时',
        n1: '工单类型',
        n2: 'ESN编号/订单编号',
        n3: '工单编号',
        n4: '登记人姓名',
        n5: '电话号码',
        n6: '创建时间',
        n7: '处理部门',
        n8: '催单',
        n9: '工单状态',
        n10: '最后处理人',
        width: '180px',
        operation: '操作',
      },
      talLength: 0,//总条数
      pageSize: 15,
      pageNum: 1,
      lastData: {},//上次搜索的条件
      jobTypeList: [{ label: '工单审核', value: '1' }, { label: '工单处理', value: '2' }, { label: '工单回访', value: '3' }, { label: '工单归档', value: '4' }],
      jobClassificationList: [],//工单分类
    }
  },
  props: [],
  created() {
    var that = this;

    window.addEventListener('offline', () => {
      // 网络由正常常到异常时触发
      console.log('断网啦')
      if (that.maskData.handleWorkOrder) {
        that.FnReleaseWorkOrder(that.maskData.row)
      }
    });
    window.addEventListener('beforeunload', function (e) {
      var e = window.event || e;
      that.FnReleaseWorkOrder(that.maskData.row)
      e.returnValue = ("确定离开当前页面吗？")
    })

    var deptId = window.sessionStorage.getItem('user') ? JSON.parse(window.sessionStorage.getItem('user')).data.deptId : '';
    deptId = deptId * 1;
    this.userMessage = JSON.parse(window.sessionStorage.getItem('user')).data;
    // 角色：4-话务员，5-审核员，6-处理员，7-回访员
    // 归档-状态-已处理
    // 审核-状态-已审核
    // 处理（回访）-状态-跟进中
    // console.log(deptId)
    switch (deptId) {
      case 4:
        this.jobTypeList = [{ label: '工单审核', value: '1' }];
        this.shoWorderDeptId = false
        break;
      case 5:
        this.shoWorderDeptId = false;
        this.orderDeptId = '1';
        this.jobTypeList = [{ label: '工单审核', value: '1' }, { label: '工单处理', value: '2' }, { label: '工单归档', value: '4' }]
        break;
      case 6:
        this.shoWorderDeptId = false;
        this.orderDeptId = '2';
        this.jobTypeList = [{ label: '工单审核', value: '1' }, { label: '工单处理', value: '2' }, { label: '工单回访', value: '3' }]
        break;
      case 7:
        this.shoWorderDeptId = false;
        this.orderDeptId = '3';
        this.jobTypeList = [{ label: '工单处理', value: '2' }, { label: '工单回访', value: '3' }, { label: '工单归档', value: '4' }]
        break;
      case 1:
        this.shoWorderDeptId = true;
        this.orderDeptId = '';
        this.jobTypeList = [{ label: '工单审核', value: '1' }, { label: '工单处理', value: '2' }, { label: '工单回访', value: '3' }, { label: '工单归档', value: '4' }]
        break;
      case 2:
        this.shoWorderDeptId = true;
        this.orderDeptId = '';
        this.jobTypeList = [{ label: '工单审核', value: '1' }, { label: '工单处理', value: '2' }, { label: '工单回访', value: '3' }, { label: '工单归档', value: '4' }]
        break;
      case 3:
        this.shoWorderDeptId = true;
        this.orderDeptId = '';
        this.jobTypeList = [{ label: '工单审核', value: '1' }, { label: '工单处理', value: '2' }, { label: '工单回访', value: '3' }, { label: '工单归档', value: '4' }]
        break;
      default:
        this.jobTypeList = [{ label: '工单审核', value: '1' }, { label: '工单处理', value: '2' }, { label: '工单回访', value: '3' }, { label: '工单归档', value: '4' }]
        break;
    }
    this.FnSearch()
    this.FnGetjobClassificationList()

  },
  mounted() {
  },
  methods: {
    FnSearch() {
      // var user = window.sessionStorage.getItem('user')?JSON.parse(window.sessionStorage.getItem('user')):'';
      var deptId = (this.userMessage.deptId) * 1;//根据deptId来决定orderDeptId
      var orderDeptId = '';
      // console.log(user,'user')
      switch (deptId) {
        case 5:
          orderDeptId = '1';
          break;
        case 6:
          orderDeptId = '2';
          break;
        case 7:
          orderDeptId = '3';
          break;
        default:
          break;
      }
      var createTimeStart = '';
      var createTimeEnd = '';
      if (this.timer) {
        createTimeStart = this.timer[0]
        createTimeEnd = this.timer[1]
      }
      this.lastData = {
        createTimeStart,//创建时间
        createTimeEnd,//
        handlePerson: this.handlePerson,//最后一次处理人
        orderNo: this.orderNo,//工单号
        esnOrderNo: this.esnOrderNo,//ESN工单号
        // orderDeptId,
        orderDeptId: this.orderDeptId,
        phoneNum: this.phoneNum,//客户号码
        workOderType: this.searchWorkOderType,//查询工单类型
        classificationName: this.classificationName.join('/'),//工单分类
        orderContent: this.orderContent,//工单内容
      }
      this.FnGetWorkOrderByConditions()
    },
    // 加载工单分类
    FnGetjobClassificationList() {
      GetClassificationList().then(res => {
        if (res.state == Code) {
          this.jobClassificationList = res.data.slice()
        }
      })
    },
    FnOvertime(e) {//返回是否超时-86400000-一天的时间戳
      var date = (new Date()).getTime();//当前时间戳
      var overtime = Date.parse(e);
      var isOverTime = ((date - overtime) - (86400000 * 3)) > 0 ? true : false
      return isOverTime
    },
    FnGetWorkOrderByConditions() {
      GetWorkOrderByConditions({
        createTimeStart: this.lastData.createTimeStart,//创建时间
        createTimeEnd: this.lastData.createTimeEnd,//
        orderNo: this.lastData.orderNo,//工单号
        esnOrderNo: this.lastData.esnOrderNo,//ESN工单号
        phoneNum: this.lastData.phoneNum,//客户号码
        handlePerson: this.lastData.handlePerson,//最后一次处理人
        orderDeptId: this.lastData.orderDeptId,
        workOderType: this.lastData.workOderType,//查询工单类型
        classificationName: this.lastData.classificationName,//查询工单分类
        orderContent: this.lastData.orderContent,//查询工单内容
        orderByTime: 1,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(res => {
        // console.log(res)
        if (res.state == Code) {
          this.tableData = [];
          this.talLength = res.count;
          var list = res.data.slice();
          list.forEach((v) => {
            this.tableData.push({
              overtime: v.orderDeptId == 4 ? false : this.FnOvertime(v.updateTime),//是否超时
              n1: this.workOderType(v.workOderType),//工单类型
              n2: v.esnOrderNo,//流水号
              n3: v.orderNo,//工单编号
              n4: v.registerPerson,//登记人姓名
              n5: v.phoneNum,//电话号码
              n6: v.createTime,//创建时间
              n7: this.handleDepartment(v.orderDeptId),//处理部门
              n8: v.additional && v.additional.length ? v.additional.length : '-',//催单
              n9: this.workOrderStatus(v.orderStatus),//工单状态
              n10: v.handlePerson,
              handleWorkOrder: v.orderDeptId == 4 ? false : true,//处理工单
              // handlingOpinions:'1',//添加处理意见
              row: v
            })
          })
        }
      })
    },
    FnExport() {//导出
      // var name = this.$route.name
      window.location.href = `${this.$prefix}/order/exportWorkOrder?createTimeStart=${this.lastData.createTimeStart}&createTimeEnd=${this.lastData.createTimeEnd}&orderNo=${this.lastData.orderNo}&esnOrderNo=${this.lastData.esnOrderNo}&handlePerson=${this.lastData.handlePerson}&orderDeptId=${this.lastData.orderDeptId}&phoneNum=${this.lastData.phoneNum}&orderByTime=1&workOderType=${this.lastData.workOderType}&classificationName=${this.lastData.classificationName}&orderContent=${this.lastData.orderContent}&Authorization=${this.getUser.token}`
    },
    FnAdditional(e) {//添加附加意见记录
      // console.log(e)
      var arr = e.length ? e.slice() : []
      var list = [];
      arr.forEach((v) => {
        v.role = this.FnReturnRole(v.handleDeptId)
        v.handleStatus = this.handleDepartment(v.handleStatus)
        list.push(v)
      })
      // console.log(list)
      return list
    },
    FnIsLock(e) {//是否锁定
      // console.log(e,'是否锁定数据') 
      console.log(e);
      LockWorkOrder({
        orderNo: e.orderNo
      }).then(res => {
        // console.log(res)
        if (res.state == Code) {
          this.$message.success(res.data)
          this.showMask = true;
          this.maskTitle = "处理工单"
          this.maskWidth = '920px'
          this.maskData = {
            circulation: true,//工单流转
            handleWorkOrder: true,
            createTime: e.createTime,//创建日期：
            registerPerson: e.registerPerson,//登记人：
            workOderNo: e.orderNo,//工单编号
            phoneNum: e.phoneNum,//
            cityarea: e.pcaName, //城市地区
            clientName: e.clientName,//客户姓名：
            esnOrderNo: e.esnOrderNo,//订单编号：
            orderNameClassification: e.orderNameClassification,//工单分类：
            workOderType: e.workOderType,//工单类型：
            workOderTypeList: this.workOderTypeList,//工单类型
            jobTypeList: this.jobTypeList,
            orderStatus: e.orderStatus,//工单状态：
            workOrderStatusList: this.workOrderStatusList,
            orderContent: e.orderContent,//工单内容：
            remark: e.remark,//备注：
            additional: this.FnAdditional(e.additional),//添加附加意见记录
            handle: this.FnAdditional(e.handle),//处理意见记录
            additionalText: '',//添加附加意见
            addHandlingText: '',//添加处理意见
            orderDeptId: '',//工单流转/归档
            addHandlingBox: this.userMessage.deptId == 4 ? false : true,//能否附加意见
            row: e
          }
        }
      })
    },
    getSortableFn(e) {//表的事件
      // console.log(e)
      if (e.type == "handleWorkOrder") {//处理工单
        this.FnIsLock(e.content.row);//先看看是否锁定
      } else if (e.type == "handlingOpinions") {//处理意见
        this.FnIsLock(e.content.row)
      } else if (e.type == 'pageSize') {
        this.pageSize = e.content;
        this.FnGetWorkOrderByConditions()
      } else if (e.type == 'pageNum') {
        this.pageNum = e.content;
        this.FnGetWorkOrderByConditions()
      } else if (e.type == 'additional') {
        this.FnAddWorkOrder(e.content.row, 1)//1添加附加意见
      }

    },
    FnAdditionalText(e) {//添加附加意见不能为空
      // console.log(e,'添加处理意见提交的数据')
      // console.log(this.userMessage,'this.userMessage')
      if (e.additionalText === '') {
        this.$message.error("添加附加意见不能为空");
        return
      }

      // handleStatus:e.orderStatus,//当前处理状态:1:审核; 2跟进中; 3:已处理;
      AddAdditionalComment({
        handleDeptId: this.userMessage.deptId,//当前登记人(部门)
        handleDetail: e.additionalText,//附加详情
        handleId: this.userMessage.orderNo,//当前登记人(工号)
        handlePerson: this.userMessage.username,//当前登记人(姓名)
        workOderNo: e.row.orderNo,//工单编号
      }).then(res => {
        // console.log(res)
        if (res.state == Code) {
          this.$message.success("添加附加意见成功");
          this.maskData.additional.push({
            createTime: res.data.createTime,
            handlePerson: res.data.handlePerson,
            role: this.FnReturnRole(res.data.handleDeptId),
            handleDetail: e.additionalText,
          })
          this.maskData.additionalText = ''
        }
      })
    },
    FnReleaseWorkOrder(e) {//释放工单
      if (!this.maskData.handleWorkOrder) {
        return
      }
      ReleaseWorkOrder({
        orderNo: e.orderNo
      }).then(res => {
        // console.log(res);
        if (res.state == Code) {
          this.$message.success(res.data)
          this.showMask = false;
          this.maskData = {}
          this.FnGetWorkOrderByConditions()
        }
      })
    },
    FnAddHandling(e) {//添加处理意见：
      // console.log(e,'添加处理意见')
      if (e.addHandlingText === '') {
        this.$message.error("添加处理意见内容不能为空")
        return
      }
      AddHandleComment({
        handleDeptId: this.userMessage.deptId,//当前登记人(部门)
        handleDetail: e.addHandlingText,//附加详情
        handleId: this.userMessage.orderNo,//当前登记人(工号)
        handlePerson: this.userMessage.username,//当前登记人(姓名)
        workOderNo: e.row.orderNo,//工单编号
      }).then(res => {
        // console.log(res)
        this.$message.success("添加处理意见成功");
        this.maskData.handle.push({
          createTime: res.data.createTime,
          handlePerson: res.data.handlePerson,
          role: this.FnReturnRole(res.data.handleDeptId),
          handleDetail: res.data.handleDetail,
        })
        this.maskData.addHandlingText = ''
      })
    },
    FnWorkOrderFlow(e) {
      // console.log(e,'工单流转')
      if (e.addHandlingText === '') {
        this.$message.error("添加处理意见内容不能为空")
        return
      }
      if (e.orderDeptId === '') {
        this.$message.error("未选择工单流转")
        return
      }
      AddWorkOrder({
        createTime: e.createdTime,
        handlePerson: this.userMessage.username,//当前登记人(姓名)
        phoneNum: e.phoneNum,//电话
        clientName: e.clientName,//客户姓名：
        esnOrderNo: e.esnOrderNo,//ESM编号/订单编号：
        orderContent: e.orderContent,//工单内容：
        handleDetail: e.orderContent,//工单内容：------
        orderNameClassification: e.orderNameClassification,
        workOderType: e.workOderType,//工单类型
        remark: e.remark,
        orderDeptId: e.orderDeptId,
        orderStatus: e.orderStatus,
        isUsed: '0',
        orderNo: e.row.orderNo,
        // handleStatus:'1',
        handleId: this.userMessage.orderNo,//-----
        handleDeptId: this.userMessage.deptId,//-----
        registerDeptId: this.userMessage.deptId,//------
        registerId: this.userMessage.orderNo,
        registerPerson: e.row.registerPerson,
        additional: JSON.stringify([{
          handlePerson: this.userMessage.username,//当前登记人(姓名)
          handleId: this.userMessage.orderNo,//-----
          handleDeptId: this.userMessage.deptId,//-----
          // handleStatus:'1',
          handleDetail: e.orderContent
        }]
        ),
        handle: JSON.stringify({
          handleDeptId: this.userMessage.deptId,//当前登记人(部门)
          handleDetail: e.addHandlingText,//附加详情
          handleId: this.userMessage.orderNo,//当前登记人(工号)
          handlePerson: this.userMessage.username,//当前登记人(姓名)
          workOderNo: e.row.orderNo,//工单编号
          handleStatus: e.orderDeptId,//流转的工单部门
        })
      }).then(res => {
        if (res.state == Code) {
          this.$message.success("处理工单成功，工单已释放");
          this.showMask = false;
          this.maskData = {}
          this.FnSearch()
        }
      })
    },
    FnMask(e) {
      // console.log(e)
      if (e.type == "false") {
        this.FnReleaseWorkOrder(this.maskData.row);//释放工单
      } else if (e.type == "additional") {//添加附加意见：
        this.FnAdditionalText(this.maskData);//添加附加意见：
      } else if (e.type == "addHandling") {//添加处理意见：
        this.FnAddHandling(this.maskData);//添加处理意见：
      } else if (e.type == "workOrderFlow") {//工单流转
        this.FnWorkOrderFlow(this.maskData);//工单流转
      }


    }

  },
  beforeDestroy() {
    //在 beforeDestroy 钩子移除beforeunload事件
    window.removeEventListener('beforeunload', this.FnReleaseWorkOrder, false);
    window.removeEventListener('offline', this.FnReleaseWorkOrder);
  },
  components: {
    ShowTable,
    Vmask
  },
  computed: {
    ...mapGetters(['getPermissionControl', 'getUser'])
  },
  watch: {

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='scss' scoped>
</style>
